/**
 * @author Yuliy Khorolinskyy
 *
 * Reaktionsspiel challengesManager
 *
 * 12.01.2012
 */
package control;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

import challengeGUI.ChallengeGUI;
import challengesManager.ChallengeManager;

import data.Player;

/**
 * @author Yuliy
 *
 */
public class KeyInputManager extends KeyAdapter {

	private Control c;
	private volatile long stopProcessingEventsAfterTS = Long.MAX_VALUE;
	private volatile long startProcessingEventsAfterTS = Long.MIN_VALUE;

	
	public KeyInputManager(Control c) {
		this.c = c;
	}
	
	public boolean isBadKey(int keyCode){
		if(keyCode == KeyEvent.VK_UNDEFINED || keyCode == KeyEvent.VK_ESCAPE)return true;
		return false;
	}
	
	public boolean isKeyInUse(int keyCode){
		for (int i = 0; i < c.players.length; i++) {
			if(c.players[i].getBuzzerKeyCode() == keyCode)return true;
		}
		return false;
	}
	
	public void playerActionIsProcessed(){
		this.startProcessingEventsAfterTS = SimpleTimer.getTimeStamp();
		this.stopProcessingEventsAfterTS = Long.MAX_VALUE;
		
	}
	
	public void disableBuzzing(){
		this.stopProcessingEventsAfterTS = SimpleTimer.getTimeStamp();
	}
	
	
	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
	 */
	@Override
	public void keyPressed(KeyEvent e) {
		switch (e.getKeyCode()) {
		case KeyEvent.VK_ESCAPE:c.abortGames();
			//TODO implement key dependant actions like pause, esc etc.
			break;

		default:
			if(stopProcessingEventsAfterTS > e.getWhen() && startProcessingEventsAfterTS < e.getWhen()){
				
				for (int i = 0; i < c.players.length ; ++i) {
					if(c.players[i].isEnabled() && e.getKeyCode() == c.players[i].getBuzzerKeyCode()){
						if(c.getCurChallMan() != null){
							System.out.println("ID " + e.getID()+ ", When " + e.getWhen()+ ", Hash " + e.hashCode()+ ", KeyCode " + e.getKeyCode() + ", Source " + e.getSource().toString());
							stopProcessingEventsAfterTS = e.getWhen();
							c.getCurChallMan().playerBuzz(c.players[i]);
						}
					}
					
				}
			}
		}
	}

}
